package com.android.webserver.manager;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.android.webserver.R;
import com.android.webserver.WebServerService;
import com.android.webserver.db.DatabaseOpenHelper;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TableLayout.LayoutParams;
import static android.view.ViewGroup.LayoutParams.FILL_PARENT;

/**
 * @author Baptiste GOURDIN
 *
 */
public class WebServerManager extends Activity
{
	Cursor				c;
	DatabaseOpenHelper	db;
	int numClients;

	public static String getLocalIpAddress()
	{
		try
		{
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();)
			{
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
						.hasMoreElements();)
				{
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress())
					{
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		}
		catch (SocketException ex)
		{
			Log.e("WebServer", ex.toString());
		}
		return null;
	}

	private class AppDetailHandler implements ImageView.OnClickListener{
		private String appPath = "";
		AppDetailHandler (String path) {
			appPath = path;
		}
		
		@Override
		public void onClick(View v) {
			Intent app = new Intent(WebServerManager.this, WebAppDetail.class);
			app.putExtra("path", appPath);
			startActivity(app);		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server);
		
		numClients = 0;
		
		if (WebServerService.DEBUG)
		{
		if (WebServerService.RUNNING == false)
			startService(new Intent(WebServerManager.this,
					WebServerService.class));
		}
		
		ScrollView sv = (ScrollView) findViewById(R.id.appList);
		db = new DatabaseOpenHelper(this);
		c = db.getApplications();
		c.moveToFirst();
		int numApps = 0;
		TableLayout tl = new TableLayout(this);
		LayoutParams lp = new LayoutParams(FILL_PARENT, FILL_PARENT);
		tl.setColumnStretchable(1, true);
		tl.setLayoutParams(lp);

		
		while (c.isAfterLast() == false) {
			String appName = c.getString(1);
			String appPath = c.getString(2);
			c.moveToNext();

			TableRow tr1 = new TableRow(this);
			ImageView appIcon = new ImageView(this);
			appIcon.setImageResource(R.drawable.icon);

			TextView name = new TextView(this);
			name.setText(appName);
			name.setPadding(10, 10, -1, -1);

			ImageView appDetailButton = new ImageView(this);
			appDetailButton.setImageResource(R.drawable.expander_ic_minimized);
			tr1.setOnClickListener(new AppDetailHandler(appPath));

			tr1.addView(appIcon);
			tr1.addView(name);
			tr1.addView(appDetailButton);
			tl.addView(tr1, lp);

		
			numApps++;
		}
		c.close();
		
		sv.addView(tl);

		TextView appsRunning = (TextView) findViewById(R.id.numAppsRunning);
		appsRunning.setText(numApps + " apps running");
		
		CheckBox serverExec = (CheckBox) findViewById(R.id.serverStatus);
		serverExec.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				CheckBox rb = (CheckBox) findViewById(R.id.serverStatus);
				if (!isChecked) {
					Log.i("WebServer", "Stop Service");
					stopService(new Intent(WebServerManager.this, WebServerService.class));
					rb.setText("   Stopped");
				} else {
					Log.i("WebServer", "start Service");
					
					// TODO: Some bug while restarting service. Fix this
					startService(new Intent(WebServerManager.this, WebServerService.class));
					rb.setText("   Running");
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu (Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.server_menu , menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.start_stop:
			break;
		case R.id.settings:
			break;
		case R.id.log:
			break;
	    }
	    return true;
	}

}
